package com.ihr360.job.core.job;

import com.ihr360.job.core.BatchStatus;
import com.ihr360.job.core.JobInterruptedException;
import com.ihr360.job.core.StartLimitExceededException;
import com.ihr360.job.core.Step;
import com.ihr360.job.core.entity.JobExecution;
import com.ihr360.job.core.entity.StepExecution;
import com.ihr360.job.core.lanuch.support.JobRestartException;
import com.ihr360.job.core.step.StepLocator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Simple implementation of {@link Job} interface providing the ability to run a
 * {@link JobExecution}. Sequentially executes a job by iterating through its
 * list of steps.  Any {@link Step} that fails will fail the job.  The job is
 * considered complete when all steps have been executed.
 *
 * @author Lucas Ward
 * @author Dave Syer
 * @author Michael Minella
 */
public class SimpleJob extends AbstractJob {

    private List<Step> steps = new ArrayList<Step>();

    /**
     * Default constructor for job with null name
     */
    public SimpleJob() {
        this(null);
    }

    /**
     * @param name
     */
    public SimpleJob(String name) {
        super(name);
    }

    /**
     * Public setter for the steps in this job. Overrides any calls to
     * {@link #addStep(Step)}.
     *
     * @param steps the steps to execute
     */
    public void setSteps(List<Step> steps) {
        this.steps.clear();
        this.steps.addAll(steps);
    }

    @Override
    public int getStepsCount() {
        return this.steps.size();
    }

    /**
     * Convenience method for clients to inspect the steps for this job.
     *
     * @return the step names for this job
     */
    @Override
    public Collection<String> getStepNames() {
        List<String> names = new ArrayList<String>();
        for (Step step : steps) {
            names.add(step.getName());

            if (step instanceof StepLocator) {
                names.addAll(((StepLocator) step).getStepNames());
            }
        }
        return names;
    }

    /**
     * Convenience method for adding a single step to the job.
     *
     * @param step a {@link Step} to add
     */
    public void addStep(Step step) {
        this.steps.add(step);
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.springframework.batch.core.job.AbstractJob#getStep(java.lang.String)
     */
    @Override
    public Step getStep(String stepName) {
        for (Step step : this.steps) {
            if (step.getName().equals(stepName)) {
                return step;
            } else if (step instanceof StepLocator) {
                Step result = ((StepLocator) step).getStep(stepName);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }

    /**
     * Handler of steps sequentially as provided, checking each one for success
     * before moving to the next. Returns the last {@link StepExecution}
     * successfully processed if it exists, and null if none were processed.
     *
     * @param execution the current {@link JobExecution}
     * @see AbstractJob#handleStep(Step, JobExecution)
     */
    @Override
    protected void doExecute(JobExecution execution) throws JobInterruptedException, JobRestartException,
            StartLimitExceededException {

        StepExecution stepExecution = null;
        for (Step step : steps) {
            stepExecution = handleStep(step, execution);
            if (stepExecution.getStatus() != BatchStatus.COMPLETED) {
                //
                // Terminate the job if a step fails
                //
                break;
            }
        }

        //
        // Update the job status to be the same as the last step
        //
        if (stepExecution != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Upgrading JobExecution status: " + stepExecution);
            }
            execution.upgradeStatus(stepExecution.getStatus());
            execution.setExitStatus(stepExecution.getExitStatus());
        }
    }

}
